<script lang="ts" setup>
import { ref } from 'vue'
import { passwordSchema } from './data'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { indexApi } from '@/api/sys/indexApi'
import { HashingFactory } from '@/utils/cipher'

defineOptions({ name: 'PasswordModal' })

const emit = defineEmits(['success', 'register'])
const title = ref('修改密码')

const [registerForm, { resetFields, validate }] = useForm({
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: passwordSchema,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(() => {
  resetFields()
  setModalProps({ confirmLoading: false })
})

async function handleSubmit() {
  try {
    const values = await validate()

    await indexApi.changePwd({
      pwd: HashingFactory.MD5().hash(values.pwd).toUpperCase(),
      newPwd: HashingFactory.MD5().hash(values.newPwd).toUpperCase(),
      confirmPwd: HashingFactory.MD5().hash(values.confirmPwd).toUpperCase(),
    })
    setModalProps({ confirmLoading: true })
    closeModal()
    emit('success')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal v-bind="$attrs" :title="title" :min-height="120" @register="registerModal" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
